package observer;

import sun.text.normalizer.TrieIterator;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;

/**
 * @Description:
 * @Author: zhangh
 * @Time: 2020/12/21 20:56
 **/
public class EventListener {
    public static HashMap<String,Event> events=new HashMap<>();

    public void addListener(String eventType,Object target) throws Exception {
        this.addListener(eventType,target,target.getClass().getMethod("on" + toUpperFirstCase(eventType),Event.class));
    }

    private void addListener(String eventType, Object target, Method method) {
        events.put(eventType,new Event(target,method));
    }

    //触发事件
    public void trigger(Event event) throws InvocationTargetException, IllegalAccessException {
        event.setTime(System.currentTimeMillis());
        event.setSource(this);
        //invoke(”实例对象“,args...)
        event.getCallBack().invoke(event.getTarget(),event);
    }

    public void trigger(String trigger) throws InvocationTargetException, IllegalAccessException {
        if(!this.events.containsKey(trigger)){return;}
        this.trigger(events.get(trigger));
    }


    //逻辑处理的私有方法，首字母大写
    private String toUpperFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] -= 32;
        return String.valueOf(chars);
    }
}
